package com.bigegg.employee.service.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.bigegg.employee.domain.*;
import com.bigegg.employee.mapper.ClassesMapper;
import com.bigegg.employee.mapper.TeacherClassMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bigegg.employee.mapper.AssistantMapper;
import com.bigegg.employee.service.IAssistantService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 辅导员Service业务层处理
 * 
 * @author 刘博
 * @date 2022-08-17
 */
@Service
public class AssistantServiceImpl implements IAssistantService 
{

    public final Logger log = LoggerFactory.getLogger(AssistantServiceImpl.class);

    @Autowired
    private AssistantMapper assistantMapper;

    @Autowired
    private TeacherClassMapper teacherClassMapper;

    @Autowired
    private CUserService cUserService;

    @Autowired
    private ClassesMapper classesMapper;

    /**
     * 查询辅导员
     * 
     * @param userId 辅导员主键
     * @return 辅导员
     */
    @Override
    public Assistant selectAssistantByUserId(Long userId)
    {
        return assistantMapper.selectAssistantByUserId(userId);
    }

    /**
     * 查询辅导员列表
     * 
     * @param assistant 辅导员
     * @return 辅导员
     */
    @Override
    public List<Assistant> selectAssistantList(Assistant assistant)
    {
        return assistantMapper.selectAssistantList(assistant);
    }

    /**
     * 新增辅导员
     * 
     * @param assistant 辅导员
     * @return 结果
     */
    @Override
    public int insertAssistant(Assistant assistant)
    {

        int result = 0;

        RegisterInfo info = new RegisterInfo();
        info.setUsername(assistant.getUserName());
        info.setPassword("000000");
        info.setNickname(assistant.getNickName());
        info.setEmail(assistant.getEmail());
        info.setPhoneNumber(assistant.getPhonenumber());

        cUserService.registerTypeUser(1, info);

        // 班级信息
        List<Classes> classesList = assistant.getClassesList();

        if(classesList!=null && classesList.size()>0){

            for(Classes c : classesList){

                TeacherClass teacherClass = new TeacherClass();

                teacherClass.setClassId(c.getId());

                teacherClass.setTeacherId(info.getId());

                this.teacherClassMapper.insertTeacherClass(teacherClass);

            }
        }

        result = 1;

        return result;
    }

    /**
     * 修改辅导员
     * 
     * @param assistant 辅导员
     * @return 结果
     */
    @Override
    public int updateAssistant(Assistant assistant)
    {
        assistant.setUpdateTime(DateUtils.getNowDate());

        return assistantMapper.updateAssistant(assistant);
    }

    /**
     * 批量删除辅导员
     * 
     * @param userIds 需要删除的辅导员主键
     * @return 结果
     */
    @Override
    public int deleteAssistantByUserIds(Long[] userIds)
    {
        return assistantMapper.deleteAssistantByUserIds(userIds);
    }

    /**
     * 删除辅导员信息
     * 
     * @param userId 辅导员主键
     * @return 结果
     */
    @Override
    public int deleteAssistantByUserId(Long userId)
    {
        return assistantMapper.deleteAssistantByUserId(userId);
    }

    /**
     * 上传excel
     */
    @Override
    public void importData(MultipartFile multipartFileile){

        InputStream is = null;
        try {
            is = multipartFileile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Assistant> list = EasyExcel.read(new BufferedInputStream(is)).head(Assistant.class).sheet().headRowNumber(1).doReadSync();

        if(list!=null && list.size()>0){

            Long cnt = 0L;

            for(Assistant assistant : list){

                // 查询这个辅导员存在不
                Assistant c = new Assistant();

                // 在模板上复制手机号作为工号，作为登录名
                c.setUserName(assistant.getUserName());

                // 根据登录名查询
                List<Assistant> assistantList = this.assistantMapper.selectAssistantList(c);

                if(assistantList==null || assistantList.size()==0){// 不存在

                    // 注册
                    RegisterInfo info = new RegisterInfo();
                    info.setUsername(assistant.getUserName());
                    info.setPassword("000000");
                    info.setNickname(assistant.getNickName());
                    info.setEmail(assistant.getEmail());
                    info.setPhoneNumber(assistant.getPhonenumber());
                    cUserService.registerTypeUser(1, info);

                    // 关联班级
                    this.relClasses(info.getId() , assistant.getClassesName());

                }else {

                    this.log.info("已存在此辅导员，无需新增，进行关联");

                    Assistant ass = assistantList.get(0);


                    // 查询班级
                    Classes classes = new Classes();
                    classes.setName(assistant.getClassesName());
                    List<Classes> classesList = this.classesMapper.selectClassesList(classes);

                    if(classesList!=null && classesList.size()>0){// 存在班级

                        Classes classesDb = classesList.get(0);

                        // 判断此班级是否已关联
                        TeacherClass teacherClass = new TeacherClass();
                        teacherClass.setTeacherId(ass.getUserId());
                        teacherClass.setClassId(classesDb.getId());

                        List<TeacherClass> teacherClassList = this.teacherClassMapper.selectTeacherClassList(teacherClass);

                        if(teacherClassList!=null && teacherClassList.size()>0){// 已关联

                            this.log.info("此辅导员和此班级已关联过");

                        }else{// 未关联

                            this.log.info("此辅导员和此班级未关联过，进行关联");

                            // 关联班级
                            this.relClasses(ass.getUserId() , assistant.getClassesName());

                        }
                    }

                }

                cnt++;
                this.log.info(String.format("已完成%d/%d",cnt,list.size()));
            }

        }
    }

    /**
     * 关联班级
     */
    public void relClasses(Long userId , String classesName){

        if(!StringUtils.isEmpty(classesName)){

            String[] cnArray = classesName.split(",");

            for(String cn : cnArray){

                Classes classes = new Classes();
                classes.setName(cn.trim());

                List<Classes> classesList = this.classesMapper.selectClassesList(classes);

                if(classesList!=null && classesList.size()>0){

                    Classes cla = classesList.get(0);

                    TeacherClass teacherClass = new TeacherClass();

                    teacherClass.setClassId(cla.getId());

                    teacherClass.setTeacherId(userId);

                    this.teacherClassMapper.insertTeacherClass(teacherClass);
                }
            }
        }
    }
}
